import React, { useEffect, useState, useRef } from 'react'
import { Button, Switch, Table, Modal } from "antd"
import {
    EditOutlined,
    DeleteOutlined,
    CloseCircleTwoTone
} from '@ant-design/icons';
import UserFrom from "../../../components/sideMenu/Form/Form"
import http from "../../../util/http"
const { confirm } = Modal;
export default function UserManage() {
    const [dataSource, setDataSource] = useState([])
    const [isModalOpen, setIsModalOpen] = useState(false)
    const [regionList, setRegionList] = useState([])
    const [roleList, setRoleList] = useState([])
    // const [title, setTitle] = useState(false)
    const [isModalUpdate, setisModalUpdate] = useState(false)
    const [isUpdate, setIsupdate] = useState(false)
    const addForm = useRef(null);
    const updateFormMessage = useRef(null);
    const columns = [{
        title: '区域',
        dataIndex: 'region',
        filters: [
            ...regionList.map(item => ({
                text: item.title,
                value: item.title
            })),
            {
                text: "全球",
                value: "全球"
            },
        ],
        onFilter: (value, item) => {
            if (value === "全球") {
                return item.region === "";
            } else {
                return item.region === value
            }
        },
        render: (region) => {
            return <b>{region === "" ? "全球" : region}</b>
        }
    },
    {
        title: "角色名称",
        dataIndex: "role",
        render: (role) => {
            return role.roleName
        }
    }, {
        title: "用户名",
        dataIndex: "username"
    }, {
        title: "用户状态",
        dataIndex: "roleState",
        render: (roleState, item) => {
            return <Switch onChange={() => change(item)} checked={roleState} disabled={item.default}></Switch >
        }
    }, {
        title: "操作",
        render: (item) => {
            return <div>
                <Button type='primary' icon={<EditOutlined />} shape="circle" disabled={item.default}
                    onClick={() => updateFrom(item)}
                ></Button>
                <Button type='primary' danger icon={<DeleteOutlined />} shape="circle"
                    onClick={() => remove(item)}
                    disabled={item.default}
                ></Button>
            </div>
        }
    }]
    const change = (item) => {
        item.roleState = !item.roleState;
        // console.log(item)
        setDataSource([...dataSource])
    }
    /* 删除 */
    const remove = (item) => {
        confirm({
            title: '确定要删除吗?',
            icon: <CloseCircleTwoTone twoToneColor="#FF0000" />,
            onOk() {
                del(item)
            },
            onCancel() {
                return
            },
        });
    }
    const del = (item) => {
        setDataSource(dataSource.filter(data => data.id !== item.id))
        http.delete(`/users/${item.id}`)

    }
    /*user */
    useEffect(() => {
        http.get("/users?_expand=role").then(res => {
            setDataSource(res.data)
        })
    }, []);
    /* 区域 */
    useEffect(() => {
        http.get("/regions").then(res => {
            let list = res.data;
            setRegionList(list)
        })
    }, []);
    /* 管理员 */
    useEffect(() => {
        http.get("/roles").then(res => {
            let list = res.data;
            setRoleList(list)
        })
    }, [])
    // 更新表单 
    const updateFrom = (item) => {
        // 同步进行 
        // console.log(item, updateFormMessage);
        // setTimeout(() => {
        //     setisModalUpdate(true)
        //     updateFormMessage.current.setFieldsValue(item).then(

        //     ).catch(err => console.log(err))
        // }, 0)
        /* 异步加载立即调用 */
        (async () => {
            await item.roleId === 1 ? setIsupdate(true) : setIsupdate(false);
            await setisModalUpdate(true);
            await updateFormMessage.current.setFieldsValue(item);
            await updateFormMessage.current.validateFields().then((data) => {
                setisModalUpdate(true);
                // axios.post()
                //  updateFormMessage.current.resetFields();  
                console.log(data)
            }).catch(err => console.log(err))
        })()

    }
    const handleOk = () => {
        addForm.current.validateFields().then(value => {
            setIsModalOpen(false)
            addForm.current.resetFields();
            console.log(value);
            http.post("/users", {
                ...value,
                default: false,
                roleState: true,
            }).then(res => {
                console.log(res.data)
                setDataSource([...dataSource, {
                    ...res.data,
                    role: roleList.filter(item => item.id === value.roleId)[0]
                }])
            })
        }).catch(err => console.log(err))
    };
    const handleCancel = () => {
        (async () => {
            await setIsModalOpen(false);
            await setisModalUpdate(false);
            await setIsupdate(!isUpdate)
        })();
    }
    return (
        <div>
            <Button danger type='primary' style={{ marginBottom: "20px" }} onClick={() => {
                setIsModalOpen(true)
                // setTitle(false);
            }}>添加用户</Button>
            <Table dataSource={dataSource} columns={columns}
                rowKey={item => item.id}
                pagination={{
                    pageSize: 5
                }}
            />
            <Modal open={isModalOpen} onOk={handleOk} onCancel={handleCancel}
                title="添加用户信息"
                cancelText="取消"
                okText="确定"
            >
                <UserFrom regionList={regionList}
                    roleList={roleList} ref={addForm}></UserFrom>
            </Modal>
            <Modal open={isModalUpdate} onOk={updateFrom} onCancel={handleCancel}
                title="修改用户信息"
                okText="更新"
                cancelText="取消"
            >
                <UserFrom regionList={regionList}
                    roleList={roleList} ref={updateFormMessage} isUpdate={isUpdate}></UserFrom>
            </Modal>
        </div >
    )
}
